import Taro, {Component, Config} from '@tarojs/taro'
import { View, ScrollView, Image } from '@tarojs/components'
import { SDBody, SDLoading } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import CommonEmptyView from '../../../comps/empty-view'

import orderStatusMapper from '../orderStatus'

import './index.less'
import SearchIcon from '../../../images/ic_search_black.png'
import EmptyIcon from '../../../images/ic_nothing_search.png'

type PageState = {
  tabBarList: any[],
  mainIsLoading: boolean,
  currentTabBarCode: string,
  dataList: any[],
  loading: boolean,
  hasData: boolean,
  hasMore: boolean,
  hideLoading: boolean
}

export default class OrderListPage extends Component<{}, PageState> {

  config: Config = {
    navigationBarTitleText: '订单列表',
    enablePullDownRefresh: true
  }

  constructor() {
    super()
    //'all' | 'pendingPayment' | 'toBeShipped' | 'toBeReceived' | 'returns'
    this.state = {
      tabBarList: [
        {
          code: 'all',
          title: '全部'
        }, {
          code: 'pendingPayment',
          title: '待付款'
        }, {
          code: 'toBeShipped',
          title: '待发货'
        }, {
          code: 'toBeReceived',
          title: '待收货'
        }, {
          code: 'returns',
          title: '退换货'
        },
      ],
      currentTabBarCode: 'all',
      mainIsLoading: true,
      dataList: [],
      hasData: true,
      hasMore: true,
      hideLoading: false,
      loading: false
    }
  }

  componentDidMount () {
    this.setState({
      currentTabBarCode: (this.$router.params || {}).tabBarCode || 'all'
    }, () => {
      this.fetchData(0, true, false)
    })
  }

  onPullDownRefresh () {
    this.fetchData(0, false, true)
  }

  onReachBottom () {
    const {dataList} = this.state
    this.fetchData(dataList.length)
  }

  fetchData = (offset = 0, resetList = false, hideLoading = false) => {
    const limit = 20
    let { loading, hasData, hasMore, dataList, currentTabBarCode } = this.state
    if (loading || (offset > 0 && !hasMore)) {
      return
    }

    if (offset == 0) {
      dataList = []
    }

    let param: any = {
      offset: offset,
      limit: limit,
      orderType: 'SALE_ORDER',    // 固定参数
    }
    ////'all' | 'pendingPayment' | 'toBeShipped' | 'toBeReceived' | 'returns'

    if (currentTabBarCode == 'pendingPayment') {
      param.orderViewStatusEnums = 'PRE_PAY'
    } else if (currentTabBarCode == 'toBeShipped') {
      param.orderViewStatusEnums = 'PRE_DELIVER'
    } else if (currentTabBarCode == 'toBeReceived') {
      param.orderViewStatusEnums = 'PRE_ACCEPT'
    }

    let pageState: any = {
      loading: true,
      hasData: true,
      hasMore: true,
      hideLoading: hideLoading || (dataList.length > 0 && dataList.length < limit)
    }
    if (resetList) {
      pageState.dataList = dataList
    }
    this.setState({
      ...pageState
    },async () => {
      try {
        if (currentTabBarCode == 'returns') { // 退换货
          dataList = []
          hasMore = false
          hasData = false

        } else {
          let resp = await SDUtils.doGet('/wxmini/order', {
            ...param
          })

          dataList = dataList.concat(resp.items || [])
          hasData = resp.total > 0
          hasMore = resp.total > dataList.length
        }

      } catch (e) {
        SDUtils.showMsg(e)
      } finally {
        Taro.stopPullDownRefresh()
        this.setState({
          mainIsLoading: false,
          loading: false,
          hasData: hasData,
          hasMore: hasMore,
          dataList: dataList,
          hideLoading: false
        })
      }
    })
  }

  render () {
    const { mainIsLoading, tabBarList, currentTabBarCode, loading, hasMore, hasData, dataList, hideLoading } = this.state
    return (
      <SDBody sd-class='container' loading={mainIsLoading}>
        <View className="nav-bar border-bottom_1px">
          <ScrollView className="bar-list" scrollX={true}>
            {
              tabBarList.map((item, index) => {
                return <View className={`bar-item ${item.code == currentTabBarCode ? 'bar-item_sel' : ''}`} key={index} onClick={this.switchMenuBar.bind(this, item.code)}>
                  <View className="content">
                    <View className="title">{item.title}</View>
                    <View className="line"></View>
                  </View>
                </View>
              })
            }
          </ScrollView>
          <View className="search-content" onClick={this.gotoSearchPage}>
            <Image className="search-icon" src={SearchIcon}></Image>
          </View>
        </View>
        <View style='height:90rpx;'></View>
        <View className="section-list">
          {
            dataList.map((item, index) => {
              return (
                <View className="section-item" onClick={this.gotoOrderDetail.bind(this, index)} key={index}>
                  <View className="header border-bottom_1px">
                    <View className="title">订单号：{item.orderNo}</View>
                    <View className="sub-title">{orderStatusMapper(item.orderViewStatusEnums)}</View>
                  </View>
                  <View className="sku-list">
                    {
                      (((item.itmes || {}).productViewVo || []).slice(0, 8)).map((innerItem, innerIndex) => {
                        return (
                          <View className="sku-item" key={innerIndex}>
                            <Image className="img" src={innerItem.image}></Image>
                            {/*<View className="tips-content">*/}
                              {/*<View className="title">20个</View>*/}
                            {/*</View>*/}
                          </View>
                        )
                      })
                    }
                  </View>
                  <View className="section-footer">
                    <View className="left">
                      <View className="l_top">
                        <View className="lt_item">商品：{item.productTotalQuantity || 0}</View>
                        <View className="lt_item">规格：{item.skuTotalQuantity}</View>
                        <View className="lt_item">总数: {item.totalQuantity}</View>
                      </View>
                      <View className="l_bottom">{SDUtils.formatDate(item.createTime)}</View>
                    </View>
                    <View className="right">
                      <View className="r_top">
                        <View className="tips">合计：</View>
                        <View className="title">{SDUtils.formatPrice(item.finalTotalAmount)}</View>
                      </View>
                      {
                        item.orderViewStatusEnums == 'PRE_PAY' ? (
                          <View className="r_bottom">
                            <View className="rb_btn">立即支付</View>
                          </View>
                        ) : null
                      }
                    </View>
                  </View>
                </View>
              )
            })

            /**
             <View className="section-item" onClick={this.gotoOrderDetail}>
             <View className="header border-bottom_1px">
             <View className="title">订单号：123456</View>
             <View className="sub-title">待付款</View>
             </View>
             <View className="sku-list">
             {
                [1,2,3,4,5,6,7,8].map((_, index) => {
                  return (
                    <View className="sku-item" key={index}>
                      <Image className="img" src=''></Image>
                      <View className="tips-content">
                        <View className="title">20个</View>
                      </View>
                    </View>
                  )
                })
              }
             </View>
             <View className="section-footer">
             <View className="left">
             <View className="l_top">
             <View className="lt_item">商品：4</View>
             <View className="lt_item">规格：36</View>
             <View className="lt_item">总数: 90</View>
             </View>
             <View className="l_bottom">2017-08-08 16:46</View>
             </View>
             <View className="right">
             <View className="r_top">
             <View className="tips">合计：</View>
             <View className="title">￥1573.00</View>
             </View>
             <View className="r_bottom">
             <View className="rb_btn">立即支付</View>
             </View>
             </View>
             </View>
             </View>

             <View className="section-item" onClick={this.gotoOrderDetail}>
             <View className="header border-bottom_1px">
             <View className="title">订单号：123456</View>
             <View className="sub-title">待发货</View>
             </View>
             <View className="sku-list">
             {
                [1,2,3,4,5,6,7,8].map((_, index) => {
                  return (
                    <View className="sku-item" key={index}>
                      <Image className="img" src=''></Image>
                      <View className="tips-content">
                        <View className="title">20个</View>
                      </View>
                    </View>
                  )
                })
              }
             </View>
             <View className="section-footer">
             <View className="left">
             <View className="l_top">
             <View className="lt_item">商品：4</View>
             <View className="lt_item">规格：36</View>
             <View className="lt_item">总数: 90</View>
             </View>
             <View className="l_bottom">2017-08-08 16:46</View>
             </View>
             <View className="right">
             <View className="r_top">
             <View className="tips">合计：</View>
             <View className="title">￥1573.00</View>
             </View>
             </View>
             </View>
             </View>

             <View className="section-item" onClick={this.gotoOrderDetail}>
             <View className="header border-bottom_1px">
             <View className="title">订单号：123456</View>
             <View className="sub-title">已完成</View>
             </View>
             <View className="sku-list">
             {
                [1,2,3,4,5,6,7,8].map((_, index) => {
                  return (
                    <View className="sku-item" key={index}>
                      <Image className="img" src=''></Image>
                      <View className="tips-content">
                        <View className="title">20个</View>
                      </View>
                    </View>
                  )
                })
              }
             </View>
             <View className="section-footer">
             <View className="left">
             <View className="l_top">
             <View className="lt_item">商品：4</View>
             <View className="lt_item">规格：36</View>
             <View className="lt_item">总数: 90</View>
             </View>
             <View className="l_bottom">2017-08-08 16:46</View>
             </View>
             <View className="right">
             <View className="r_top">
             <View className="tips">合计：</View>
             <View className="title">￥1573.00</View>
             </View>
             </View>
             </View>
             </View>

             <View className="section-item">
             <View className="header border-bottom_1px">
             <View className="title">订单号：123456</View>
             <View className="sub-title">已作废</View>
             </View>
             <View className="sku-list">
             {
                [1,2,3,4,5,6,7,8].map((_, index) => {
                  return (
                    <View className="sku-item" key={index}>
                      <Image className="img" src=''></Image>
                      <View className="tips-content">
                        <View className="title">20个</View>
                      </View>
                    </View>
                  )
                })
              }
             </View>
             <View className="section-footer">
             <View className="left">
             <View className="l_top">
             <View className="lt_item">商品：4</View>
             <View className="lt_item">规格：36</View>
             <View className="lt_item">总数: 90</View>
             </View>
             <View className="l_bottom">2017-08-08 16:46</View>
             </View>
             <View className="right">
             <View className="r_top">
             <View className="tips">合计：</View>
             <View className="title">￥1573.00</View>
             </View>
             </View>
             </View>
             </View>

             <View className="section-item" onClick={this.gotoOrderDetail}>
             <View className="header border-bottom_1px">
             <View className="title">订单号：123456</View>
             <View className="sub-title">待收货</View>
             </View>
             <View className="sku-list">
             {
                [1,2,3,4,5,6,7,8].map((_, index) => {
                  return (
                    <View className="sku-item" key={index}>
                      <Image className="img" src=''></Image>
                      <View className="tips-content">
                        <View className="title">20个</View>
                      </View>
                    </View>
                  )
                })
              }
             </View>
             <View className="section-footer">
             <View className="left">
             <View className="l_top">
             <View className="lt_item">商品：4</View>
             <View className="lt_item">规格：36</View>
             <View className="lt_item">总数: 90</View>
             </View>
             <View className="l_bottom">2017-08-08 16:46</View>
             </View>
             <View className="right">
             <View className="r_top">
             <View className="tips">合计：</View>
             <View className="title">￥1573.00</View>
             </View>
             </View>
             </View>
             </View>

             <View className="section-item" onClick={this.gotoReturnsDetail}>
             <View className="header border-bottom_1px">
             <View className="title">订单号：123456</View>
             <View className="sub-title">（退货）待审核</View>
             </View>
             <View className="sku-list">
             {
                [1,2,3,4,5,6,7,8].map((_, index) => {
                  return (
                    <View className="sku-item" key={index}>
                      <Image className="img" src=''></Image>
                      <View className="tips-content">
                        <View className="title">20个</View>
                      </View>
                    </View>
                  )
                })
              }
             </View>
             <View className="section-footer">
             <View className="left">
             <View className="l_top">
             <View className="lt_item">商品：4</View>
             <View className="lt_item">规格：36</View>
             <View className="lt_item">总数: 90</View>
             </View>
             <View className="l_bottom">2017-08-08 16:46</View>
             </View>
             <View className="right">
             <View className="r_top">
             <View className="tips">合计：</View>
             <View className="title">￥1573.00</View>
             </View>
             </View>
             </View>
             </View>

             */
          }

        </View>
        <SDLoading loading={loading} hasMore={hasMore} hasData={hasData} hideLoading={hideLoading}>
          <CommonEmptyView title='暂无数据' icon={EmptyIcon} />
        </SDLoading>
      </SDBody>
    )
  }

  switchMenuBar = (code: string) => {
    const { currentTabBarCode } = this.state
    if (code == currentTabBarCode) { return }
    this.setState({
      currentTabBarCode: code
    }, () => {
      this.fetchData(0, true, false)
    })
  }

  gotoSearchPage = () => {
    SDUtils.jumpTo('/pages/order/search/form/index')
  }

  gotoOrderDetail = (index: number) => {
    const { dataList } = this.state
    if (index >= dataList.length) {
      return
    }
    let dataItem = dataList[index]
    SDUtils.jumpTo('/pages/order/detail/index', {orderId: dataItem.orderId})
  }

  gotoReturnsDetail = () => {
    SDUtils.jumpTo('/pages/order/returns/detail/index')
  }
}
